package com.example.demo.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

/**
 * @Author: Pinp
 * @Date: 2021/7/23 13:40
 */

@Slf4j
@Configuration
public class ApplicationSslSup {


    @Autowired
    private Environment env;

    /**
     * 配置内置的servlet容器工厂为tomcat.
     * @return
     */
    @Bean
    public ServletWebServerFactory servletContainer() {

//        log.warn(env.getProperty("server.ssl.key-store"));

        if (env.getProperty("server.ssl.key-store") == null){
            return new TomcatServletWebServerFactory();
        }


        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                securityConstraint.addCollection(collection);
                context.addConstraint(securityConstraint);
            }
        };
        //添加连接配置，主要是http的配置信息.
        tomcat.addAdditionalTomcatConnectors(redirectConnector());
        return tomcat;
    }

    /**
     * 配置一个http连接信息.
     * @return
     */
    private Connector redirectConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setPort(80);
        connector.setSecure(false);
        connector.setRedirectPort(Integer.parseInt(env.getProperty("server.port")));
        return connector;
    }

}
